#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

from app import db
from app.fwmap import fwmap
from app.fwmap import restfulApi
from flask_restful import Resource
from app.fwmap.model import Fwmapp, Position
from app.public import ResultJson, paginates
from flask import render_template, request
import json

# 主页
@fwmap.route('/<int:position>', endpoint='index')
def index(position):
    return render_template('fwIndex.html')


# 添加页面
@fwmap.route('/fwmapcreate/<int:pid>')
def fwmapcreate(pid):
    return render_template('fwMapcreate.html')


# 修改页面
@fwmap.route('/fwmapedit/<path:pid>')
def fwmapedit(pid):
    return render_template('fwMapEdit.html')


#   传递 rest 风格接口, 主页form数据展示， 删除
class FwmapindexApi(Resource):
    def get(self, pid):
        position = Position.query.get(pid)
        result = ResultJson()  # 实例
        if position:
            queryset = position.maps  # print(position.maps)  ==  Fwmapp.query.order_by('id')
            paginate, page_range = paginates(request, queryset)  # 获取分页
            result.count = paginate.total  # 获取总行数
            # 循环数据列表，并给它整成字典
            for fwmap in paginate.items: result.data.append(fwmap.to_add_json())
        return result.to_json()

    def delete(self, pid):
        result = ResultJson()  # 实例
        if Fwmapp.query.get(pid):
            db.session.query(Fwmapp).filter_by(id=pid).delete()
            db.session.commit()
            result.code = 10000
        return result.to_json()


# 前台渲染input的地址， 创建映射关系
class GetAddress(Resource):
    def get(self):
        result = ResultJson()
        tablename = request.args.get("tablename")
        position = request.args.get("position")
        if check_table(tablename):
            sql = "select * from {0} where position_id = {1}".format(tablename, position)
            if all([db.session.execute(sql).fetchall(), ]):
                result.code = 10000
                address_list = [(u.id, u.address) for u in db.session.execute(sql).fetchall()]
                result.data.append(address_list)
        # 如果是其它的类型的错误， 统一直接全返回首页
        return result.to_json()

    def post(self):
        # 将前台获取的类json字符串转成json格式
        data = json.loads(str(request.data, 'utf-8'))
        result = ResultJson()
        # 先检验是否为空， 如果不为空在继续往下走
        if all([v for k, v in data.items()]):
            print('-----------------------------------')

            print(data)
            checks = check(data)
            if not checks:
                result.code = 10000
                instance = Fwmapp(**data)
                db.session.add(instance)
                db.session.commit()
            else:
                result.code = 10001
                result.data.append(checks)
        return result.to_json()


# 编辑接口， 渲染页面，加修改
class FwmapEdit(Resource):
    def get(self):
        result = ResultJson()
        queryset = Fwmapp.query.get(request.args["changeid"])
        if queryset:
            result.code = 10000
            result.data.append(queryset.to_json())
        return result.to_json()

    def put(self):
        result = ResultJson()
        changeDic = json.loads(str(request.data, 'utf-8'))
        queryset = Fwmapp.query.filter_by(serialnumber=changeDic["serialnumber"]).first()
        if all([queryset]):
            for key, value in changeDic.items():
                if hasattr(queryset, key):
                    setattr(queryset, key, value)
                db.session.commit()
                result.code = 10000
        return result.to_json()


# 检验表是否存在
def check_table(tablemap):
    # 如果返回的值存在, 那么就返回这个表名称， 不存在就是空列表了
    res = [tablemap for table in db.session.execute("show tables").fetchall() if tablemap == table[0]]
    # 如果是空的 就让它返回false, 否则就是true
    return True if all([res, ]) else False


# 用于判断 序列号跟ID是否存在
def check(data):
    sdic = {}
    seid = ["serialnumber", "sequenceid"]

    for id in seid:
        print(data)
        sql = 'select * from fw_firewalld where serialnumber = {0}'.format(data[id])
        if all([db.session.execute(sql).fetchone()]):
            sdic[id] = "{0}已存在".format(id)

    sql = 'select * from fw_firewalld where inaddress="{0}" and inport = "{1}" and outaddress = "{2}" ' \
          'and outport = "{3}"'.format(data["inaddress"], data["inport"], data["outaddress"], data["outport"])
    if all([db.session.execute(sql).fetchone()]):
        sdic["inport"] = "{0}已存在".format("inport")
        sdic["outport"] = "{0}已存在".format("outport")

    out = 'select * from fw_firewalld where outaddress = "{0}" and outport = "{1}"'.format(data["outaddress"],
                                                                                        data["outport"])
    if all([db.session.execute(out).fetchone()]):
        sdic["outport"] = "外网地址跟端口已存在"

    return sdic


restfulApi.add_resource(FwmapindexApi, '/FwmapindexApi/<pid>', endpoint="FwmapindexApi")
restfulApi.add_resource(GetAddress, '/GetAddress', endpoint="GetAddress")
restfulApi.add_resource(FwmapEdit, '/FwmapEdit', endpoint="FwmapEdit")
